<template>
  <div class="app-container">
 

    <el-row :gutter="10" class="mb8">
 

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseList" @selection-change="handlePurchaseSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购单号" align="center" prop="id" >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)">{{ scope.row.id }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)">{{ parseTime(scope.row.createTime) }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applyUserName">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)">{{ scope.row.applyUserName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="auditorUserName" />
      <el-table-column label="使用项目" align="center" prop="usedProject" />
      <el-table-column label="采购描述" align="center" prop="remark" />
      <el-table-column label="采购总数" align="center" prop="totalCount" />
      <el-table-column label="已收数量" align="center" prop="receivedQuantity" />
      <el-table-column label="待收数量" align="center" prop="waitedQuantity" />
      <el-table-column label="总金额(元)" align="center" prop="totalWithTax" />
      <el-table-column label="已付款(元)" align="center" prop="totalPaidAmount" />
      <el-table-column label="应付款(元)" align="center" prop="totalPayableAmount" />
      <el-table-column label="采购状态" align="center" prop="purchaseCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.purchase_code" :value="scope.row.purchaseCode"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              v-hasPermi="['purchase:order:edit']"
          >采购操作</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 新增/编辑采购申请单弹窗 -->
    <div>
      <!-- 主要弹窗：编辑/查看采购申请 -->
      <el-dialog
          :title="title"
          :visible.sync="showEditArea"
          append-to-body
          @close="cancelEdit"
          :width="getDialogWidth()"
          class="responsive-dialog"
          style="margin-top: 30px; height: 90vh;"
      >
        <!-- 滚动内容区域 -->
        <div class="dialog-content-wrapper" style="flex-shrink: 0; padding: 10px 0;">
          <!-- 表单 -->
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="使用项目" prop="usedProject">
                  <el-input v-model="form.usedProject" type="text" placeholder="输入使用项目" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="申请人" prop="applyUserName">
                  <el-input v-model="form.applyUserName" type="text" placeholder="申请人" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="采购申请时间" prop="requestTime">
                  <el-input v-model="form.requestTime" type="text" placeholder="自动生成" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建时间" prop="createTime">
                  <el-input v-model="form.createTime" type="text" placeholder="自动生成" disabled />
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="采购总数" prop="totalCount">
                  <el-input v-model="form.totalCount" placeholder="自动计算" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="已收数量" prop="receivedQuantity">
                  <el-input v-model="form.receivedQuantity" placeholder="自动计算" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="待收数量" prop="waitedQuantity">
                  <el-input v-model="form.waitedQuantity" placeholder="自动计算" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="总金额(元)" prop="totalWithTax">
                  <el-input v-model="form.totalWithTax" placeholder="自动计算" disabled />
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="已付款(元)" prop="totalPaidAmount">
                  <el-input v-model="form.totalPaidAmount" placeholder="自动计算" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="应付款(元)" prop="totalPayableAmount">
                  <el-input v-model="form.totalPayableAmount" placeholder="自动计算" disabled />
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="申请描述" prop="remark">
                  <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="合同附件" prop="contractUrl">
                  <file-upload v-model="form.contractUrl" :limit="1" placeholder="物料规格书" disabled/>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 采购子项 -->
            <el-divider style="margin: 6px 0; font-size: 14px;">采购单子项</el-divider>

            <!-- 子项筛选条件 -->
            <el-form :model="detailFilterParams" ref="detailFilterForm" size="small" :inline="true" style="margin-bottom: 10px;">
              <el-form-item label="票据状态" prop="billCode">
                <el-select v-model="detailFilterParams.billCode" placeholder="选择票据状态" clearable style="width: 150px;">
                  <el-option
                      v-for="dict in dict.type.bill_code"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="采购状态" prop="purchaseCode">
                <el-select v-model="detailFilterParams.purchaseCode" placeholder="选择采购状态" clearable style="width: 150px;">
                  <el-option
                    v-for="dict in dict.type.purchase_code"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDetailFilter">筛选</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetDetailFilter">重置</el-button>
              </el-form-item>
            </el-form>

 

            <!-- 物料选择组件（弹窗） -->
            <ItemSelect ref="itemSelect" @onSelected="onItemSelected" />

            <!-- 子项表格 -->
            <el-table
                :data="formattedDetailList"
                style="margin-top: 0;"
                @selection-change="handleDetailSelectionChange"
                row-key="id"
                :key="tableKey"
                lazy
                :load="loadChildItems"
                default-expand-all
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                :row-class-name="getRowClassName"
                ref="treeTable"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="产品编码1" align="center" prop="itemCode" width="120">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="handleEditDetail(scope.$index, scope.row)">
                    {{ scope.row.itemCode }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="产品名称" align="center" prop="itemName" />
              <el-table-column label="单位" align="center" prop="unitOfMeasure" width="80"  />
              <el-table-column label="物料图片" align="center" prop="itemImgUrl" width="80">
                <template slot-scope="scope">
                  <image-preview v-if="scope.row.itemImgUrl" :src="scope.row.itemImgUrl" :width="50" :height="50" />
                </template>
              </el-table-column>

              <el-table-column label="供应商" align="center" prop="vendorName" width="180">
                <template slot-scope="scope">
                  <el-input
                      v-model="scope.row.vendorName"
                      placeholder="请选择供应商"
                      size="mini"
                      style="width: 150px;"
                      :disabled="isDetailActionDisabled(scope.row) || scope.row.purchaseCode === 2"
                      @focus="handleSelectVendorFromTable(scope.row, scope.$index)"
                  >
                    <el-button
                        slot="append"
                        icon="el-icon-search"
                        @click.native="handleSelectVendorFromTable(scope.row, scope.$index)"
                        :disabled="isDetailActionDisabled(scope.row) || scope.row.purchaseCode === 2"
                    />
                  </el-input>
                </template>
              </el-table-column>

              <!-- 采购总数列 -->
<!--               <el-table-column label="采购总数" align="center" prop="quantity" width="140">
                <template slot-scope="scope">
                  <el-input-number
                      :disabled="scope.row.purchaseCode >= 3 || scope.row.purchaseCode === 2"
                      v-model="scope.row.quantity"
                      :min="1"
                      :controls="true"
                      :precision="2"
                      controls-position=""
                      size="mini"
                      @change="(value) => handleQuantityChange(value, scope.row)"
                  />
                </template>
              </el-table-column> -->

              <!-- 已购数量列 -->
              <el-table-column label="已购数量" align="center" prop="purchasedQuantity" width="180">
                <template slot-scope="scope">
                  <el-input-number
                      :disabled="scope.row.purchaseCode >= 3 || scope.row.purchaseCode === 2"
                      v-model="scope.row.purchasedQuantity"
                      :min="0"
                      :controls="true"
                      :precision="2"
                      controls-position=""
                      size="mini"
                      style="width: 160px;"
                      @change="(value) => handlePurchasedQuantityChange(value, scope.row)"
                  />
                </template>
              </el-table-column>



              <el-table-column label="已收数量" align="center" prop="receivedQuantity" width="180">
                <template slot-scope="scope">
                  <el-input-number
                      :disabled="scope.row.purchaseCode === 2"
                      v-model="scope.row.receivedQuantity"
                      :min="0"
                      :controls="true"
                      :precision="2"
                      controls-position=""
                      size="mini"
                      style="width: 160px;"
                      @change="(value) => handleReciveQuantityChange(value, scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="待收数量" align="center" prop="waitedQuantity" width="220" />

              <!-- 入库批次号列 -->
              <el-table-column label="入库批次号" align="center" prop="inboundBatchCode" width="160">
                <template slot-scope="scope">
                  <el-input
                      v-model="scope.row.inboundBatchCode"
                      placeholder="入库批次号"
                      size="mini"
                      style="width: 130px;"
                      :disabled="scope.row.purchaseCode === 2"
                      @change="(value) => handleInboundBatchCodeChange(value, scope.row)"
                  />
                </template>
              </el-table-column>

              <!-- 仓库选择列 -->
              <el-table-column label="仓库" align="center" prop="warehouseName" width="200" >
                <template slot-scope="scope">
                  <el-cascader
                      v-model="scope.row.warehouseInfo"
                      :options="warehouseOptions"
                      :props="warehouseProps"
                      :disabled="scope.row.purchaseCode === 2"
                      placeholder="选择仓库"
                      size="mini"
                      style="width: 170px;"
                      @change="(value) => handleWarehouseChanged(value, scope.row)"
                      clearable
                  />
                </template>
              </el-table-column>

              <!-- 库区选择列 -->
              <el-table-column label="库区" align="center" prop="locationName" width="150">
                <template slot-scope="scope">
                  <el-input
                      v-model="scope.row.locationName"
                      placeholder="库区"
                      size="mini"
                      style="width: 120px;"
                      readonly
                      :disabled="scope.row.purchaseCode === 2"
                  />
                </template>
              </el-table-column>

              <!-- 库位选择列 -->
              <el-table-column label="库位" align="center" prop="areaName" width="150">
                <template slot-scope="scope">
                  <el-input
                      v-model="scope.row.areaName"
                      placeholder="库位"
                      size="mini"
                      style="width: 120px;"
                      readonly
                      :disabled="scope.row.purchaseCode === 2"
                  />
                </template>
              </el-table-column>
 
              <!-- 采购状态列 -->
              <el-table-column label="采购状态" align="center" prop="purchaseCode" width="100">
                <template slot-scope="scope">
                  <el-tag
                    :class="getPurchaseCodeTagClass(scope.row.purchaseCode)"
                    size="mini"
                  >
                    {{ getPurchaseCodeText(scope.row.purchaseCode) }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column label="时间" align="center" prop="createTime" width="100"/>
              <el-table-column label="操作11" >
                <template slot-scope="scope">
                  <!-- 入库按钮 -->
                  <el-button
                    size="mini"
                    type="success"
                    icon="el-icon-coin"
                    color="green"
                    circle
                    @click="handleInbound(scope.row)"
                  
                    title="入库"
                    v-hasPermi="['purchase:detail:tostore']"
                  ></el-button>
                  <span v-if="scope.row._isTemp || scope.row.isTemp" style="color: #f56c6c; font-size: 12px;">临时</span>
                </template>
              </el-table-column>
            </el-table>

          </el-form>

        </div>

        <!-- 底部按钮 -->
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
        </div>
      </el-dialog>

    </div>

    <!-- 查看采购单详情弹窗 -->
    <el-dialog
        title="查看采购单详情"
        :visible.sync="showViewArea"
        append-to-body
        @close="cancelView"
        :width="getDialogWidth()"
        class="responsive-dialog"
        style="margin-top: 30px; height: 90vh;"
    >
      <!-- 滚动内容区域 -->
      <div class="dialog-content-wrapper" style="flex-shrink: 0; padding: 10px 0;">
        <!-- 表单 -->
        <el-form ref="viewForm" :model="form" label-width="120px" :disabled="true">
          <el-row>
            <el-col :span="6">
              <el-form-item label="使用项目" prop="usedProject">
                <el-input v-model="form.usedProject" type="text" placeholder="输入使用项目" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="申请人" prop="applyUserName">
                <el-input v-model="form.applyUserName" type="text" placeholder="申请人" disabled />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="采购申请时间" prop="requestTime">
                <el-input v-model="form.requestTime" type="text" placeholder="自动生成" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建时间" prop="createTime">
                <el-input v-model="form.createTime" type="text" placeholder="自动生成" disabled />
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="采购总数" prop="totalCount">
                <el-input v-model="form.totalCount" placeholder="自动计算" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="已收数量" prop="receivedQuantity">
                <el-input v-model="form.receivedQuantity" placeholder="自动计算" disabled />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="待收数量" prop="waitedQuantity">
                <el-input v-model="form.waitedQuantity" placeholder="自动计算" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="总金额(元)" prop="totalWithTax">
                <el-input v-model="form.totalWithTax" placeholder="自动计算" disabled />
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="已付款(元)" prop="totalPaidAmount">
                <el-input v-model="form.totalPaidAmount" placeholder="自动计算" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="应付款(元)" prop="totalPayableAmount">
                <el-input v-model="form.totalPayableAmount" placeholder="自动计算" disabled />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="申请描述" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同附件" prop="contractUrl">
                <div v-if="form.contractUrl">
                  <a :href="form.contractUrl" target="_blank" class="attachment-link">
                    {{ getFileName(form.contractUrl) }}
                  </a>
                </div>
                <div v-else style="color: #909399;">暂无附件</div>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 采购子项 -->
          <el-divider style="margin: 6px 0; font-size: 14px;">采购单子项</el-divider>

          <!-- 子项筛选条件 -->
          <el-form :model="detailFilterParams" ref="detailFilterForm" size="small" :inline="true" style="margin-bottom: 10px;">
            <el-form-item label="票据状态" prop="billCode">
              <el-select v-model="detailFilterParams.billCode" placeholder="选择票据状态" clearable style="width: 150px;">
                <el-option
                    v-for="dict in dict.type.bill_code"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="采购状态" prop="purchaseCode">
              <el-select v-model="detailFilterParams.purchaseCode" placeholder="选择采购状态" clearable style="width: 150px;">
                <el-option
                  v-for="dict in dict.type.purchase_code"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleDetailFilter">筛选</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetDetailFilter">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 子项表格 -->
          <el-table
              :data="formattedDetailList"
              style="margin-top: 0;"
              row-key="id"
              :key="tableKey"
              lazy
              :load="loadChildItems"
              default-expand-all
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              :row-class-name="getRowClassName"
              ref="viewTreeTable"
          >
            <el-table-column label="产品编码" align="center" prop="itemCode" width="120" />
            <el-table-column label="产品名称" align="center" prop="itemName" />
            <el-table-column label="单位" align="center" prop="unitOfMeasure" width="80"  />
            <el-table-column label="物料图片" align="center" prop="itemImgUrl" width="80">
              <template slot-scope="scope">
                <image-preview v-if="scope.row.itemImgUrl" :src="scope.row.itemImgUrl" :width="50" :height="50" />
              </template>
            </el-table-column>

            <el-table-column label="供应商" align="center" prop="vendorName" width="200" />

            <!-- 采购总数列 -->
            <el-table-column label="采购总数" align="center" prop="quantity" width="140" />

            <!-- 已购数量列 -->
            <el-table-column label="已购数量" align="center" prop="purchasedQuantity" width="140" />

            <!-- 未购数量列 -->
            <el-table-column label="未购数量" align="center" prop="unpurchasedQuantity" width="140">
              <template slot-scope="scope">
                <span :class="[
                  'unpurchased-quantity',
                  scope.row.unpurchasedQuantity > 0 ? 'warning' : 'success'
                ]">
                  {{ scope.row.unpurchasedQuantity }}
                </span>
              </template>
            </el-table-column>

            <el-table-column label="已收数量" align="center" prop="receivedQuantity" width="220" />
            <el-table-column label="待收数量" align="center" prop="waitedQuantity" width="220" />

            <!-- 采购状态列 -->
            <el-table-column label="采购状态" align="center" prop="purchaseCode" width="100">
              <template slot-scope="scope">
                <el-tag
                  :class="getPurchaseCodeTagClass(scope.row.purchaseCode)"
                  size="mini"
                >
                  {{ getPurchaseCodeText(scope.row.purchaseCode) }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="时间" align="center" prop="createTime" width="100"/>
          </el-table>

        </el-form>

      </div>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelView">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 编辑采购单子项弹窗 -->
    <el-dialog :title="editDetailDialogTitle" :visible.sync="editDetailDialogVisible" width="1000px" append-to-body>
      <el-form ref="editDetailFormRef" :model="editDetailForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购单ID" prop="purchaseId">
              <el-input v-model="editDetailForm.purchaseId" placeholder="请输入采购申ID" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称" prop="itemName">
              <el-input v-model="editDetailForm.itemName" placeholder="请输入产品名称" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品编码" prop="itemCode">
              <el-input v-model="editDetailForm.itemCode" placeholder="请输入产品编码" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商" prop="vendorName">
              <el-input
                  v-model="editDetailForm.vendorName"
                  placeholder="请选择供应商"
                  :disabled="isDetailActionDisabled(editDetailForm)"
                  @focus="handleSelectVendorFromDialog"
              >
                <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click.native="handleSelectVendorFromDialog"
                />
              </el-input>
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="editDetailForm.specification" type="textarea" placeholder="请输入规格型号" maxlength="100" disabled show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="editDetailForm.unitOfMeasure" placeholder="单位" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="票据状态" prop="billCode" disabled>
              <el-select v-model="editDetailForm.billCode" placeholder="票据状态" @change="handleEditBillCodeChange" disabled>
                <el-option v-for="dict in dict.type.bill_code" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="物料图片" prop="itemImgUrl" label-width="110px">
              <image-preview :src="editDetailForm.itemImgUrl" :width="200" :height="200" v-if="editDetailForm.itemImgUrl"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购物品截图" prop="screenShotUrl" label-width="110px"  >
              <image-upload v-model="editDetailForm.screenShotUrl" :limit="1"  :disabled="isDetailActionDisabled(editDetailForm)"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购总数" prop="quantity"  >
              <el-input v-model="editDetailForm.quantity" placeholder="请输入数量" :disabled="editDetailForm.purchaseCode >= 3"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="已购数量" prop="purchasedQuantity">
              <el-input v-model="editDetailForm.purchasedQuantity" placeholder="请输入已购数量" :disabled="editDetailForm.purchaseCode >= 3" @change="handleEditPurchasedQuantityChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="未购数量" prop="unpurchasedQuantity"  >
              <el-input v-model="editDetailForm.unpurchasedQuantity" placeholder="未购数量" disabled/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="已收数量" prop="receivedQuantity"  label-width="100px" >
              <el-input v-model="editDetailForm.receivedQuantity" placeholder="请输入内容" :disabled="isDetailActionDisabled(editDetailForm)" @change="handleEditReceivedQuantityChange" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="待收数量" prop="waitedQuantity"  label-width="100px" >
              <el-input v-model="editDetailForm.waitedQuantity" placeholder="待收数量" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="快递公司" prop="shippingCarrier"  label-width="100px" disabled >
              <el-input v-model="editDetailForm.shippingCarrier" placeholder="快递公司"  disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="快递单号" prop="trackingNumber"  label-width="100px"  disabled>
              <el-input v-model="editDetailForm.trackingNumber" placeholder="快递单号" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="单价(元)" prop="unitPrice"  label-width="100px" >
              <el-input v-model="editDetailForm.unitPrice" placeholder="请输入内容" :disabled="isDetailActionDisabled(editDetailForm)" @change="handleEditUnitPriceChange" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="已付金额(元)" prop="paidAmount" label-width="120px">
              <el-input v-model="editDetailForm.paidAmount" placeholder="请输入内容"   disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="应付金额(元)" prop="payableAmount" label-width="120px">
              <el-input v-model="editDetailForm.payableAmount" placeholder="请输入内容"  disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="时间" prop="createTime" >
              <el-input v-model="editDetailForm.createTime" placeholder="请输入内容"  disabled style="width: 165px;"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购地址" prop="buyAddres"  >
              <el-input v-model="editDetailForm.buyAddres" type="textarea" placeholder="请输入采购地址" :disabled="isDetailActionDisabled(editDetailForm)"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="editDetailForm.remark" type="textarea" placeholder="请输入备注" :disabled="isDetailActionDisabled(editDetailForm)"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            附件:<file-upload
              v-if="!isDetailActionDisabled(editDetailForm)"
              v-model="editDetailForm.attachmentUrl"
              :limit="1"
              placeholder="附件"
          />
            <!-- 禁用时显示提示 -->
            <div v-else class="upload-placeholder">
              <template v-if="editDetailForm.attachmentUrl">
                附件：
                <a
                    :href="editDetailForm.attachmentUrl"
                    :title="getFileName(editDetailForm.attachmentUrl)"
                    target="_blank"
                    class="attachment-link"
                >
                  {{ getFileName(editDetailForm.attachmentUrl) }}
                </a>
              </template>
              <template v-else>
                暂无附件
              </template>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveEditDetail">确 定</el-button>
        <el-button @click="cancelEditDetail">取 消</el-button>
      </div>
    </el-dialog>

    <!--订单子项-->
    <!-- 放在 el-dialog 外面，和 table 同级 全局唯一 -->

    <VendorSelect
        ref="vendorSelect"
        @onSelected="onVendorSelected"
    />


  </div>
</template>

<script>
import { listPurchase, getPurchase, delPurchase, addPurchase, updatePurchase, applyPurchase, handlerAudit, submitPurchase, generaterItemrecpt, addAllPurchase } from "@/api/purchase/order/purchase-order";
import ItemSelect from "@/components/itemSelect/item-purchase.vue"
import { listOrderDetail, getOrderDetail, delOrderDetail, addOrderDetail, updateOrderDetail, historyPrices,toSaveStore } from "@/api/purchase/order/purchase-order-detail";
import VendorSelect from "@/components/vendorSelect/single.vue";
import { getTreeList } from "@/api/mes/wm/warehouse";

export default {
  name: "PurchaseApply",
  dicts: ['purchase_request_status', 'purchase_code', 'bill_code', 'process_code'],
  components: {
    VendorSelect,
    ItemSelect
  },
  data() {
    return {
      activeTab: 'list',
      historyPriceDialogVisible: false,
      historyPriceList: [], // 历史价格数据
      currentItemName: '',  // 当前产品名称
      tableRefreshKey: 0, // 用于强制刷新表格
      currentEditSource: null, // 'table' 或 'dialog'
      currentTableRow: null,   // 当前表格行数据
      currentTableIndex: null,
      // 是否显示弹出层
      open: false,
      isEdit: false,
      optType: null,
      loading: false,
      ids: [],
      single: true,
      multiple: true,
      delDetails: [],
      showSearch: true,
      total: 0,
      detailPageNum: 1,
      detailPageSize: 10,
      detailTotal: 0,
      // 采购申请单表格数据
      purchaseList: [],
      title: "",
      showEditArea: false, // 控制编辑区域显示
      showViewArea: false, // 控制查看区域显示
      form: {},
      rules: {
        vendorName: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
      },
      detailList: [], // 子项本地暂存
      editDetailIndex: null, // 当前编辑的子项索引
      editDetail: {}, // 当前编辑的子项
      purchaseIds: [],
      detailIds: [], // 子项表格选中的ID数组
      // 修复：初始化 queryParams，避免未定义报错
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: '',
        applyUserName: '',
        totalCount: '',
        purchaseCode: 3
      },
      // 查询参数
      detailQueryParams: {
        pageNum: 1,
        pageSize: 10,
        // ... 其他查询参数
      },
      // 编辑采购单子项弹窗
      editDetailDialogVisible: false,
      editDetailDialogTitle: '编辑采购单子项',
      editDetailForm: {},
      delDetailIds: [], //删除非临时子项主键
      tableKey: new Date().getTime(), // 用于强制刷新表格
      detailFilterParams: {
        billCode: '',
        purchaseCode: ''
      },
      // 仓库相关数据
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
        checkStrictly: true
      }
    };
  },
  computed: {
    isViewMode() {
      return this.optType === 'view';
    },
    dialogWidth() {
      const width = window.innerWidth;
      return width < 768 ? '90%' : '900px';
    },
    // 计算最低价
    minPrice() {
      return Math.min(...this.historyPriceList.map(i => i.unitPrice));
    },
    // 计算最高价
    maxPrice() {
      return Math.max(...this.historyPriceList.map(i => i.unitPrice));
    },
    // 计算平均价
    avgPrice() {
      const sum = this.historyPriceList.reduce((a, b) => a + b.unitPrice, 0);
      return this.historyPriceList.length ? sum / this.historyPriceList.length : 0;
    },
    // 格式化后的明细列表，用于树形展示
    formattedDetailList() {
      // 应用筛选条件
      let filteredList = this.detailList;

      // 筛选票据状态
      if (this.detailFilterParams.billCode !== '') {
        filteredList = filteredList.filter(item => item.billCode === this.detailFilterParams.billCode);
      }

      // 筛选采购状态
      if (this.detailFilterParams.purchaseCode !== '') {
        filteredList = filteredList.filter(item => item.purchaseCode === this.detailFilterParams.purchaseCode);
      }

      // 筛选出父项（没有parentId的项）
      const parentItems = filteredList.filter(item => !item.parentId);

      // 为每个父项添加子项标记
      parentItems.forEach(parent => {
        // 查找所有子项（parentId等于当前父项id的项）
        const children = filteredList.filter(item => item.parentId === parent.id);

        // 确保每个项目都有children数组
        if (!parent.children) {
          parent.children = [];
        }

        // 如果有子项，则设置hasChildren为true，用于懒加载
        if (children.length > 0) {
          parent.hasChildren = true;
        } else {
          // 如果没有子项，但未购数量大于0，则标记为有子项（用于动态加载）
          if (parent.unpurchasedQuantity > 0) {
            parent.hasChildren = true;
          } else {
            parent.hasChildren = false;
          }
        }
      });

      return parentItems;
    }
  },
  created() {
    this.getList();
    this.getWarehouseList();
  },
  methods: {
    /** 查询采购申请单列表 */
    getList() {
      this.loading = true;
      this.queryParams.purchaseCode = 3;
      listPurchase(this.queryParams).then(response => {
        this.purchaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        console.error('获取采购申请单列表失败：', error);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.isEdit = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.showEditArea = true;
      this.isEdit = true;
      this.optType = "add";
      this.title = "添加采购单";
      // 确保 detailList 为空
      this.detailList = [];
      // 初始化表单字段，避免无数据
      const now = new Date();
      const pad = n => n < 10 ? '0' + n : n;
      const formatDate = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
      this.form = {
        usedProject: '',
        applyUserName: '',
        remark: '',
        contractUrl: '',
        requestTime: formatDate(now),
        createTime: formatDate(now),
        totalCount: '0.00',
        totalWithTax: 0,
        receivedQuantity: 0,
        waitedQuantity: 0,
        totalPaidAmount: 0,
        totalPayableAmount: 0
      };
    },
    /** 编辑按钮操作 */
    handleEdit(row) {
      this.reset();
      this.showEditArea = true;
      this.isEdit = true;
      this.optType = "edit";
      this.title = "修改采购单信息";
      // 先清空 detailList，避免旧数据干扰
      this.detailList = [];
      getPurchase(row.id).then(response => {
        this.form = response.data || {};
        this.getDetailListPage(row.id);
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      this.isEdit = false;
      this.optType = "view";
      // 先清空 detailList，避免旧数据干扰
      this.detailList = [];
      getPurchase(row.id).then(response => {
        this.form = response.data;
        this.showViewArea = true; // 使用查看弹窗
        this.title = "查看采购单信息";
        // 检查 this.form.requestTime 是否为长整型，并进行相应的转换
        if (typeof this.form.requestTime === 'number' && this.form.requestTime.toString().length >= 10) {
          let date = new Date(this.form.requestTime);
          this.form.requestTime = date.getFullYear() + "-" +
            ("0" + (date.getMonth() + 1)).slice(-2) + "-" +
            ("0" + date.getDate()).slice(-2) + " " +
            ("0" + date.getHours()).slice(-2) + ":" +
            ("0" + date.getMinutes()).slice(-2) + ":" +
            ("0" + date.getSeconds()).slice(-2);
        }
        this.getDetailListPage(row.id);
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.purchaseIds || this.purchaseIds;
      console.log('删除rows', row);
      this.$modal.confirm('是否确认删除采购申请单编号为"' + ids + '"的数据项？').then(function () {
        return delPurchase(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    generaterItemrecptHandler() {
      const ids = this.purchaseIds;
      if (ids.length > 1) {
        this.$modal.alertError("只能选择一项");
        return false;
      }
      this.$modal.confirm('是否确认采购单"' + ids + '"转为入库单？').then(function () {
        return generaterItemrecpt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("转换成功");
      }).catch(() => { });
    },
    // 取消按钮
    cancel() {
      this.showEditArea = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.detailList = [];
      this.editDetail = {};
      this.editDetailIndex = null;
      this.delDetailIds = [];
      this.showEditArea = false;
      this.showViewArea = false;
      this.resetForm && this.resetForm("form");
    },
    /** 采购申请单表格多选框选中数据 */
    handlePurchaseSelectionChange(selection) {
      this.purchaseIds = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 申请单子项表格多选框选中数据 */
    handleDetailSelectionChange(selection) {
      console.log('----handleDetailSelectionChange-selection- ', selection);
      this.detailIds = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.delDetails = selection;
    },
    // 动态设置弹窗宽度（响应式）
    getDialogWidth() {
      const width = window.innerWidth;
      if (width < 768) {
        return '95%';
      } else if (width < 1024) {
        return '85%';
      } else {
        return '70%';
      }
    },
    // 金额文本框失焦时保留两位小数
    onBlurDecimal(row, key) {
      if (row[key] !== undefined && row[key] !== null && row[key] !== '') {
        let val = parseFloat(row[key]);
        if (!isNaN(val)) {
          row[key] = val.toFixed(2);
        }
      }
    },
    // 单价专用，兼容输入非数字时清空，允许小数点输入
    onBlurDecimal2(row, key) {
      // 获取输入的原始值
      const input = row[key];

      // 1. 如果输入为空、null 或 undefined，直接清空
      if (input === null || input === undefined || input === '') {
        row[key] = '';
        return; // 提前返回
      }

      // 2. 转换为字符串并清理：移除所有非数字和非小数点的字符
      let cleanedStr = String(input).replace(/[^0-9.]/g, '');

      // 3. 处理小数点数量：确保最多只有一个有效的小数点
      const dotIndex = cleanedStr.indexOf('.');
      if (dotIndex !== -1) {
        // 找到第一个小数点后，移除其后的所有字符中的小数点
        // 保留第一个小数点前的部分 + 第一个小数点 + 第一个小数点后部分（不含小数点）
        cleanedStr = cleanedStr.substring(0, dotIndex) + '.' + cleanedStr.substring(dotIndex + 1).replace(/\./g, '');
      }
      // 如果没有小数点，cleanedStr 保持不变

      // 4. 特殊情况：如果清理后只剩下小数点 '.' 或为空，则视为无效
      if (cleanedStr === '.' || cleanedStr === '') {
        row[key] = '';
        return;
      }

      // 5. 尝试将清理后的字符串解析为浮点数
      const parsedValue = parseFloat(cleanedStr);

      // 6. 验证解析结果
      if (isNaN(parsedValue)) {
        // 解析失败（理论上在当前清理规则下很难发生，但保险起见）
        row[key] = '';
      } else {
        // 7. 格式化为保留两位小数的字符串
        // toFixed(2) 会进行四舍五入
        row[key] = parsedValue.toFixed(2);
      }
    },
    // 获取文件名
    getFileName(url) {
      if (!url) return '';
      try {
        const urlObj = new URL(url);
        const pathname = urlObj.pathname;
        return pathname.substring(pathname.lastIndexOf('/') + 1);
      } catch (e) {
        // 如果不是有效的URL，尝试从字符串中提取文件名
        const parts = url.split('/');
        return parts[parts.length - 1] || url;
      }
    },
    // 计算未购数量
    calcUnpurchasedQuantity(item) {
      const quantity = parseFloat(item.quantity) || 0;//采购总数
      const purchasedQuantity = parseFloat(item.purchasedQuantity) || 0;//已购数量
      const unpurchasedQuantity = Math.max(0, quantity - purchasedQuantity);//未购数量
      console.log('未购 calcUnpurchasedQuantity ----', unpurchasedQuantity);
      // 更新未购数量
      this.$set(item, 'unpurchasedQuantity', parseFloat(unpurchasedQuantity.toFixed(2)));

      return unpurchasedQuantity;
    },
    // 批量计算所有子项的未购数量
    calcAllUnpurchasedQuantities() {
      this.detailList.forEach(item => {
        this.calcUnpurchasedQuantity(item);
      });
    },
    // 子项筛选方法
    handleDetailFilter() {
      // 强制刷新表格以应用筛选
      this.tableKey = new Date().getTime();
    },
    // 重置子项筛选条件
    resetDetailFilter() {
      this.detailFilterParams = {
        billCode: '',
        purchaseCode: ''
      };
      // 强制刷新表格
      this.tableKey = new Date().getTime();
    },
    // 根据采购单状态设置行样式
    getRowClassName({ row }) {
      // 对于子项表格，使用主表单的 purchaseCode
      // 对于主表格，使用行数据的 purchaseCode
      const purchaseCode = row.purchaseCode !== undefined ? row.purchaseCode : this.form.purchaseCode;

      switch (purchaseCode) {
        case 1:
          return 'row-cancelled'; // 取消采购 - 红色/灰色
        case 2:
          return 'row-draft disabled-row'; // 草稿状态 - 灰色且禁用
        case 3:
          return 'row-purchasing'; // 采购中 - 橙色
        case 4:
          return 'row-ordered'; // 已下单 - 浅蓝色
        case 5:
          return 'row-receiving'; // 收货中 - 橙色
        case 6:
          return 'row-shipped'; // 已发货 - 浅蓝色
        case 7:
          return 'row-pending-bill'; // 带补票据 - 红色
        case 8:
          return 'row-completed'; // 处理完成 - 绿色
        default:
          return '';
      }
    },
    // 根据采购状态设置标签样式
    getPurchaseCodeTagClass(purchaseStatus) {
      switch (purchaseStatus) {
        case 1:
          return 'purchase-status-cancelled'; // 取消采购 - 红色/灰色
        case 2:
          return 'purchase-status-draft'; // 草稿状态 - 灰色
        case 3:
          return 'purchase-status-purchasing'; // 采购中 - 橙色
        case 4:
          return 'purchase-status-ordered'; // 已下单 - 浅蓝色
        case 5:
          return 'purchase-status-receiving'; // 收货中 - 橙色
        case 6:
          return 'purchase-status-shipped'; // 已发货 - 浅蓝色
        case 7:
          return 'purchase-status-pending-bill'; // 带补票据 - 红色
        case 8:
          return 'purchase-status-completed'; // 处理完成 - 绿色
        default:
          return 'purchase-status-unknown'; // 未知状态 - 灰色
      }
    },
    // 根据采购状态获取中文文本
    getPurchaseCodeText(purchaseStatus) {
      switch (purchaseStatus) {
        case 1:
          return '取消采购';
        case 2:
          return '草稿状态';
        case 3:
          return '采购中';
        case 4:
          return '已下单';
        case 5:
          return '收货中';
        case 6:
          return '已发货';
        case 7:
          return '带补票据';
        case 8:
          return '处理完成';
        default:
          return '未知';
      }
    },
    // 检查并自动更新采购子项状态
    checkAndUpdatePurchaseStatus(row) {
      console.log('checkAndUpdatePurchaseStatus--row', row);

      // 只有当采购状态 >= 3 时才进行自动状态更新
      if (row.purchaseCode < 3) {
        return;
      }

      const unitPrice = parseFloat(row.unitPrice) || 0;
      const trackingNumber = row.trackingNumber || '';
      const receivedQuantity = parseFloat(row.receivedQuantity) || 0;
      const purchasedQuantity = parseFloat(row.purchasedQuantity) || 0;
      const billCode = parseInt(row.billCode) || 0;

      // 计算待收数量
      const waitedQuantity = purchasedQuantity - receivedQuantity;

      // 条件1: 如果采购状态 >= 3 且填写了单价，则采购状态变成 4已下单
      if (unitPrice > 0) {
        row.purchaseCode = 4;
        console.log(`采购子项 ${row.itemName || row.id} 状态自动更新为: 已下单 (4)`);
        return;
      }

      // 条件2: 如果采购状态 >= 3 且填写了快递单号，则采购状态变成 6已发货
      if (trackingNumber.trim() !== '') {
        row.purchaseCode = 6;
        console.log(`采购子项 ${row.itemName || row.id} 状态自动更新为: 已发货 (6)`);
        return;
      }

      // 条件3: 如果已购数量 > 0 且待收数量 > 0，则采购状态变成 5收货中
      if (purchasedQuantity > 0 && waitedQuantity > 0) {
        row.purchaseCode = 5;
        console.log(`采购子项 ${row.itemName || row.id} 状态自动更新为: 收货中 (5)`);
        return;
      }

      // 条件4: 如果已购数量 > 0 且待收数量 <= 0 且票据为 2有票据，则采购状态变成 8处理完成
      if (purchasedQuantity > 0 && waitedQuantity <= 0 && billCode === 2) {
        row.purchaseCode = 8;
        console.log(`采购子项 ${row.itemName || row.id} 状态自动更新为: 处理完成 (8)`);
        return;
      }

      // 条件5: 如果已购数量 > 0 且待收数量 <= 0 且票据为 1无票据，则采购状态变成 7带补票据
      if (purchasedQuantity > 0 && waitedQuantity <= 0 && billCode === 1) {
        row.purchaseCode = 7;
        console.log(`采购子项 ${row.itemName || row.id} 状态自动更新为: 带补票据 (7)`);
        return;
      }
    },
    // 快递单号变化处理
    handleTrackingNumberChange() {
      this.checkAndUpdatePurchaseStatus(this.editDetailForm);
    },
    // 编辑弹窗单价变化处理
    handleEditUnitPriceChange() {
      this.checkAndUpdatePurchaseStatus(this.editDetailForm);
    },
    // 编辑弹窗已收数量变化处理
    handleEditReceivedQuantityChange() {
      this.checkAndUpdatePurchaseStatus(this.editDetailForm);
    },
    // 编辑弹窗票据状态变化处理
    handleEditBillCodeChange() {
      this.checkAndUpdatePurchaseStatus(this.editDetailForm);
    },
    // 取消编辑
    cancelEdit() {
      this.showEditArea = false;
      this.reset();
    },
    // 取消查看
    cancelView() {
      this.showViewArea = false;
      this.reset();
    },
    // 获取子项列表
    getDetailListPage(requestId) {
      console.log('getDetailListPage requestId====', requestId);
      console.log('getDetailListPage this.form====', this.form);
      if (!requestId) return;
      this.detailLoading = true;
      // 1. 【关键步骤】在发起请求前，先提取并保存当前的临时数据
      const tempDetails = this.detailList.filter(item => item.isTemp);
      this.detailQueryParams.purchaseId = requestId;
      this.detailQueryParams.orderBy = "created_at";
      this.detailQueryParams.orderType = "asc";

      listOrderDetail(this.detailQueryParams)
        .then(response => {
          // 2. 获取后端返回的持久化数据
          const persistedDetails = response.rows;
          const backendTotal = response.total; // 后端返回的持久化数据总数

          // 3. 【关键步骤】合并数据：将持久化数据放在前面，临时数据放在后面
          this.detailList = [...persistedDetails, ...tempDetails];
          // 计算未购数量并初始化新字段
          this.detailList.forEach(item => {
            this.calcUnpurchasedQuantity(item);
            // 在获取数据时，确保每个父项都有初始化的 children 数组
            this.detailList.forEach(item => {
              if (!item.parentId && !item.children) {
                this.$set(item, 'children', []);
              }
            });
            
            // 确保每个项目都有新的入库相关字段
            if (!item.inboundBatchCode) {
              this.$set(item, 'inboundBatchCode', this.generateInboundBatchCode());
            }
            if (!item.warehouseInfo) {
              this.$set(item, 'warehouseInfo', []);
            }
            if (!item.warehouseId) {
              this.$set(item, 'warehouseId', null);
            }
            if (!item.warehouseName) {
              this.$set(item, 'warehouseName', '');
            }
            if (!item.locationId) {
              this.$set(item, 'locationId', null);
            }
            if (!item.locationName) {
              this.$set(item, 'locationName', '');
            }
            if (!item.areaId) {
              this.$set(item, 'areaId', null);
            }
            if (!item.areaName) {
              this.$set(item, 'areaName', '');
            }
          });
          console.log('xxxxxxxxxxxxx');

          // 获取历史价格数据
          this.fetchAllHistoryPrices();

          // ✅ 关键：只有在此处调用 calcHeaderFields，数据才是最新的！
          this.calcHeaderFields();

          // 4. 【关键步骤】计算包含临时数据的总条数
          this.detailTotal = backendTotal + tempDetails.length;
          this.detailLoading = false;
          console.log('0000----detailList--', this.detailList);

        })
        .catch(() => {
          this.detailLoading = false;
        });
    },
    // 加载子项数据（用于树形表格懒加载）
    loadChildItems(tree, treeNode, resolve) {
      // 直接返回已存在的子项
      const children = this.detailList.filter(item => item.parentId === tree.id);
      resolve(children);
    },
    // 自动计算表头统计字段
    calcHeaderFields() {
      // 先将 detailList 转换成树形结构
      const buildTree = (items) => {
        const itemMap = {};
        const tree = [];

        // 创建映射
        items.forEach(item => {
          itemMap[item.id] = { ...item, children: [] };
        });

        // 构建树
        items.forEach(item => {
          if (item.parentId) {
            // 子节点
            if (itemMap[item.parentId]) {
              itemMap[item.parentId].children.push(itemMap[item.id]);
            }
          } else {
            // 根节点
            tree.push(itemMap[item.id]);
          }
        });

        return tree;
      };

      // 递归计算树中所有节点的 purchasedQuantity 总和
      const calculateTotalPurchasedQuantity = (nodes) => {
        let total = 0;
        nodes.forEach(node => {
          total += (Number(node.purchasedQuantity) || 0);
          if (node.children && node.children.length > 0) {
            total += calculateTotalPurchasedQuantity(node.children);
          }
        });
        return total;
      };

      // 构建树并计算采购总数
      const tree = buildTree(this.detailList);
      const totalPurchasedQuantity = calculateTotalPurchasedQuantity(tree);

      this.$set(this.form, 'totalCount', parseFloat(totalPurchasedQuantity.toFixed(2)));
      console.log('calcHeaderFields---this.detailList', this.detailList);
      console.log('采购总数==', totalPurchasedQuantity);

      // 已收数量 = 所有子项的 receivedQuantity 之和（保留2位小数）
      this.form.receivedQuantity = parseFloat(
        this.detailList
          .reduce((sum, item) => sum + (Number(item.receivedQuantity) || 0), 0)
          .toFixed(2)
      );

      // 待收数量 = 所有子项的 waitedQuantity 之和（保留2位小数）
      this.form.waitedQuantity = parseFloat(
        this.detailList
          .reduce((sum, item) => sum + (Number(item.waitedQuantity) || 0), 0)
          .toFixed(2)
      );

      // 总金额 = 所有子项的 totalWithTax 之和
      this.form.totalWithTax = this.detailList.reduce((sum, item) => sum + (Number(item.totalWithTax) || 0), 0);
      // 已付款 = 所有子项的 paidAmount 之和
      this.form.totalPaidAmount = this.detailList.reduce((sum, item) => sum + (Number(item.paidAmount) || 0), 0);
      // 应付款 = 所有子项的 payableAmount 之和
      this.form.totalPayableAmount = this.detailList.reduce((sum, item) => sum + (Number(item.payableAmount) || 0), 0);

      // 重新计算所有子项的未购数量
      this.calcAllUnpurchasedQuantities();
    },
    // 添加物料子项
    openItemSelect() {
      this.$refs.itemSelect && this.$refs.itemSelect.show && this.$refs.itemSelect.show();
    },
    // 物料选择回调，支持多选、去重、临时ID
    onItemSelected(items) {
      if (!items || items.length === 0) return;
      items.forEach(element => {
        // 检查是否已存在相同物料
        const existingItem = this.detailList.find(item => item.itemId === element.itemId);
        if (existingItem) {
          this.$message.error(`物料 ${element.itemName}(${element.itemCode}) 已存在，请勿重复添加`);
          return;
        }
        // 创建临时子项对象，透传产品编号、名称、单位、物料图片等
        // 注意：新添加的物料项作为根父类（第一层），parentId为null
        const now = new Date();
        const tempDetail = {
          id: 'temp_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
          itemId: element.itemId,
          itemCode: element.itemCode,
          itemName: element.itemName,
          specification: element.specification,
          unitOfMeasure: element.unitOfMeasure,
          itemImgUrl: element.imgUrl || element.itemImgUrl || '',
          quantity: '1.00',
          purchasedQuantity: 0,
          unpurchasedQuantity: '1.00',
          purchaseCode: 2, // 默认草稿状态
          unitPrice: 0,
          totalWithTax: 0,
          receivedQuantity: '0.00',
          waitedQuantity: '0.00',
          paidAmount: 0,
          payableAmount: 0,
          vendorId: null, // 供应商ID
          vendorName: '', // 供应商名称
          vendorCode: '', // 供应商编码
          // 新增入库相关字段
          inboundBatchCode: this.generateInboundBatchCode(), // 默认入库批次号
          warehouseInfo: [], // 仓库选择数组
          warehouseId: null,
          warehouseName: '',
          locationId: null,
          locationName: '',
          areaId: null,
          areaName: '',
          isTemp: true, // 标记为临时数据
          parentId: null, // 父项ID，null表示根父类（第一层）
          createTime: this.formatDate(now),
          hasChildren: false // 是否有子项（最多两层结构）
        };
        this.detailList.push(tempDetail);

        // 为新添加的物料获取历史价格
        this.fetchLatestHistoryPrice(tempDetail);
      });
      this.calcHeaderFields();
    },
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(d.getDate()).padStart(2, '0');
      const hour = String(d.getHours()).padStart(2, '0');
      const minute = String(d.getMinutes()).padStart(2, '0');
      const second = String(d.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 获取单个物料的最新历史价格
    async fetchLatestHistoryPrice(row) {
      if (!row.itemCode) return;

      try {
        const res = await historyPrices({
          itemId: row.itemId,
          itemCode: row.itemCode
        });

        const historyData = res.data || [];
        if (historyData.length > 0) {
          // 按时间排序，获取最新的价格记录
          const sortedData = historyData.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
          const latestRecord = sortedData[0];

          // 更新行数据
          this.$set(row, 'latestHistoryPrice', latestRecord.unitPrice);
          this.$set(row, 'latestHistoryPriceDate', latestRecord.createTime);
        } else {
          this.$set(row, 'latestHistoryPrice', null);
          this.$set(row, 'latestHistoryPriceDate', null);
        }
      } catch (err) {
        console.error('获取历史价格失败：', err);
        this.$set(row, 'latestHistoryPrice', null);
        this.$set(row, 'latestHistoryPriceDate', null);
      }
    },
    // 批量获取历史价格
    async fetchAllHistoryPrices() {
      const promises = this.detailList
        .filter(item => item.itemCode && !item.parentId) // 只处理有物料编码且是父项的数据
        .map(item => this.fetchLatestHistoryPrice(item));

      await Promise.all(promises);
    },
    // 历史价格
    handleViewHistoryPrice(row) {
      this.currentItemName = row.itemName || row.itemCode;
      console.log('----handleViewHistoryPrice row--', row);
      historyPrices({
        itemId: row.itemId,
        itemCode: row.itemCode
      }).then(res => {
        this.historyPriceList = res.data || [];

        // 显示弹窗
        this.historyPriceDialogVisible = true;

        // ✅ 在 nextTick 中渲染图表（确保 DOM 已生成）
        this.$nextTick(() => {
          this.renderPriceChart();
        });
      }).catch(err => {
        this.$modal.msgError('获取历史价格失败：' + err.message);
        this.historyPriceList = [];
        this.historyPriceDialogVisible = true;
      });
    },
    renderPriceChart() {
      // 防止重复初始化
      if (this.priceChartInstance) {
        this.priceChartInstance.dispose();
      }

      const chartDom = this.$refs.priceChart;
      if (!chartDom) return;

      const echarts = require('echarts'); // 按需引入
      this.priceChartInstance = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const item = params[0].data;
            return `
            日期：${item.date}<br/>
            单价：${item.value} 元<br/>
            供应商：${item.vendorName}<br/>
            单号：${item.purchaseId}
          `;
          }
        },
        xAxis: {
          type: 'category',
          data: this.historyPriceList.map(i => i.createTime),
          axisLabel: { rotate: 30 }
        },
        yAxis: {
          type: 'value',
          name: '单价 (元)',
          min: 'dataMin',
          max: 'dataMax'
        },
        series: [
          {
            name: '采购单价',
            type: 'line',
            data: this.historyPriceList.map(i => ({
              value: i.unitPrice,
              date: i.createTime,
              vendorName: i.vendorName,
              purchaseId: i.purchaseId
            })),
            smooth: true,
            itemStyle: { color: '#e65018' },
            emphasis: { focus: 'series' },
            markPoint: {
              data: [
                { type: 'max', name: '最高价' },
                { type: 'min', name: '最低价' }
              ]
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        }
      };

      this.priceChartInstance.setOption(option);

      // 窗口大小变化时自适应
      window.addEventListener('resize', () => {
        this.priceChartInstance?.resize();
      });
    },
    // 判断是否禁用添加/批量删除按钮
    isDetailActionDisabled(row = null) {
      let status;
      if (row) {
        // 如果传入了行数据，使用行数据的采购状态
        status = row.purchaseCode;
      } else {
        // 否则使用主表单的采购状态
        status = this.form.purchaseCode;
      }
      // 如果采购状态为1、2、7、8，则禁用
      if (status === 1 || status === 2 || status === 7 || status === 8) {
        return true;
      }
      // 如果采购状态>=3，则禁用
      if (status >= 3) {
        return true;
      }
      return false;
    },
    handleConfirmPurchaseDisabled(row) {
      let status;
      if (row) {
        // 如果传入了行数据，使用行数据的采购状态
        status = row.purchaseCode;
      }

      let formStatus = this.form.purchaseCode;
      //表头采购状态 为草稿状态、取消状态、则让用
      if (!formStatus || formStatus === 1 || formStatus === 2) {
        return true;
      }
      // 只要采购状态为1或>=3，则禁用
      if (status === 1 || status >= 3) {
        return true;
      }
      return false;
    },
    // 数量变化处理
    handleQuantityChange(value, row) {
      row.quantity = value;
      // 计算未购数量
      this.calcUnpurchasedQuantity(row);

      this.updateTotalWithTax(row);
      this.calcHeaderFields();
    },
    // 已购数量变化处理
    handlePurchasedQuantityChange(value, row) {
      row.purchasedQuantity = value;
      // 计算未购数量
      this.calcUnpurchasedQuantity(row);

      // 重新计算待收数量 = 已购数量 - 已收数量
      const purchasedQuantity = parseFloat(row.purchasedQuantity) || 0;
      const receivedQuantity = parseFloat(row.receivedQuantity) || 0;
      row.waitedQuantity = parseFloat((purchasedQuantity - receivedQuantity).toFixed(2));

      this.calcHeaderFields();
    },
    // 已收数量变化处理
    handleReciveQuantityChange(value, row) {
      // 确保 value 和 purchasedQuantity 是数字
      const received = parseFloat(value) || 0;
      const purchasedQuantity = parseFloat(row.purchasedQuantity) || 0;

      row.receivedQuantity = received;

      // 待收数量 = 已购数量 - 已收数量
      row.waitedQuantity = parseFloat((purchasedQuantity - received).toFixed(2));
      this.calcHeaderFields();
      // 检查并自动更新状态
      this.checkAndUpdatePurchaseStatus(row);
    },
    // 单价变化处理
    handleUnitPriceChange(value, row) {
      row.unitPrice = value;
      this.updateTotalWithTax(row);
      this.calcHeaderFields();
      // 检查并自动更新状态
      this.checkAndUpdatePurchaseStatus(row);
    },
    // 已付款变化处理
    handlePaidAmountChange(value, row) {
      row.paidAmount = value;
      this.updateTotalWithTax(row);
      this.calcHeaderFields();
    },
    // 金额自动计算
    updateTotalWithTax(row) {
      // 兼容精度，若有 Decimal.js 可用其，否则用普通乘除
      const purchasedQuantity = Number(row.purchasedQuantity) || 0;
      const unitPrice = Number(row.unitPrice) || 0;
      const paidAmount = Number(row.paidAmount) || 0;
      // 总金额 = 已购数量 * 单价
      const totalWithTax = (purchasedQuantity * unitPrice).toFixed(2);
      row.totalWithTax = totalWithTax;
      // 应付款 = 总金额 - 已付款
      let payableAmount = (totalWithTax - paidAmount).toFixed(2);
      row.payableAmount = payableAmount > 0 ? payableAmount : '0.00';
    },
    // 票据状态变化处理
    handleBillCodeChange(value, row) {
      const updateData = {
        id: row.id,
        purchaseId: this.form.id,
        billCode: value
      };
      updateOrderDetail(updateData).then(response => {
        this.$modal.msgSuccess("修改成功");
        // 检查并自动更新状态
        this.checkAndUpdatePurchaseStatus(row);
        this.getList();
      }).catch(() => {
        // 如果保存失败，回滚数量
        // row.quantity = this.oldQuantity;
      });
    },
    // 编辑子项
    handleEditDetail(index, row) {
      this.editDetailDialogVisible = true;
      this.editDetailDialogTitle = '编辑采购单子项';
      this.editDetailForm = { ...row };
      // 计算未购数量
      this.editDetailForm.unpurchasedQuantity = (this.editDetailForm.quantity || 0) - (this.editDetailForm.purchasedQuantity || 0);
      this.editDetailIndex = index;
      this.isEdit = true;
      this.form.purchaseCode = row.purchaseCode;
      // 检查并自动更新状态
      this.checkAndUpdatePurchaseStatus(this.editDetailForm);
    },
    // 删除子项
    handleDeleteDetail(index, row) {
      // 检查删除权限
      if (row.parentId) {
        // 子节点：直接检查当前节点的采购状态
        if (row.purchaseCode >= 3) {
          const nodeName = row.itemName || row.itemCode || `节点${row.id}`;
          this.$modal.msgError(`子节点"${nodeName}"采购状态 >= 3，不能删除`);
          return;
        }
      } else {
        // 主节点：检查主节点本身和所有子节点的采购状态
        // 检查主节点本身
        if (row.purchaseCode >= 3) {
          const nodeName = row.itemName || row.itemCode || `节点${row.id}`;
          this.$modal.msgError(`主节点"${nodeName}"采购状态 >= 3，不能删除`);
          return;
        }

        // 检查子节点
        if (row.children && row.children.length > 0) {
          const restrictedChildren = row.children.filter(child => child.purchaseCode >= 3);
          if (restrictedChildren.length > 0) {
            const nodeName = row.itemName || row.itemCode || `节点${row.id}`;
            const childNames = restrictedChildren.map(child =>
              child.itemName || child.itemCode || `子节点${child.id}`
            ).join('、');
            this.$modal.msgError(`主节点"${nodeName}"包含采购状态 >= 3 的子节点：${childNames}，不能删除`);
            return;
          }
        }
      }

      // 删除当前项及其所有子项
      const itemsToDelete = [row.id];

      // 查找所有子项
      const children = this.detailList.filter(item => item.parentId === row.id);
      children.forEach(child => itemsToDelete.push(child.id));

      // 记录删除前的长度
      const oldLength = this.detailList.length;

      // 过滤掉要删除的项
      this.detailList = this.detailList.filter(item => !itemsToDelete.includes(item.id));

      // 记录删除后的长度
      const newLength = this.detailList.length;

      // 如果实际删除了项目，则更新父项的hasChildren标记
      if (oldLength !== newLength) {
        // 如果删除的是子项，需要检查父项是否还有其他子项
        if (row.parentId) {
          const parentItem = this.detailList.find(item => item.id === row.parentId);
          if (parentItem) {
            // 检查是否还有其他子项
            const hasOtherChildren = this.detailList.some(item =>
              item.parentId === row.parentId && item.id !== row.id
            );

            // 更新父项的hasChildren标记
            if (parentItem.hasChildren && !hasOtherChildren) {
              this.$set(parentItem, 'hasChildren', false);
            }
          }
        } else {
          // 如果删除的是父项，需要检查是否有子项依赖于它
          const hasChildren = this.detailList.some(item => item.parentId === row.id);
          if (!hasChildren) {
            // 没有子项依赖于这个父项，直接更新hasChildren标记
            row.hasChildren = false;
          } else {
            // 有子项依赖于这个父项，需要重新设置它们的parentId为null或者处理为独立项
            this.detailList.forEach(item => {
              if (item.parentId === row.id) {
                item.parentId = null;
                // 确保这些项现在是顶级项
                if (!item.children) {
                  this.$set(item, 'children', []);
                }
                this.$set(item, 'hasChildren', false);
              }
            });
          }
        }
      }

      // 重新计算表头字段
      this.calcHeaderFields();

      // 强制刷新表格以正确显示层级关系
      this.tableKey = new Date().getTime();

      this.$message.success("删除成功");
    },
    // 增加子节点
    handleAddChildNode(row) {
      // 检查是否为根父类（没有parentId）
      if (row.parentId) {
        this.$message.warning("只能为根父类添加子节点");
        return;
      }

      // 创建新的子节点
      const now = new Date();
      const newChildItem = {
        id: 'temp_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
        purchaseId: this.form.id,
        parentId: row.id, // 设置父项ID
        itemId: row.itemId,
        itemCode: row.itemCode,
        itemName: row.itemName,
        specification: row.specification,
        unitOfMeasure: row.unitOfMeasure,
        itemImgUrl: row.itemImgUrl,
        quantity: '1.00', // 默认数量
        purchasedQuantity: 0,
        unpurchasedQuantity: '1.00',
        purchaseCode: 2, // 草稿状态
        unitPrice: row.unitPrice || 0,
        totalWithTax: 0,
        receivedQuantity: '0.00',
        waitedQuantity: '0.00',
        paidAmount: 0,
        payableAmount: 0,
        vendorId: row.vendorId,
        vendorCode: row.vendorCode,
        vendorName: row.vendorName,
        // 新增入库相关字段
        inboundBatchCode: this.generateInboundBatchCode(), // 默认入库批次号
        warehouseInfo: [], // 仓库选择数组
        warehouseId: null,
        warehouseName: '',
        locationId: null,
        locationName: '',
        areaId: null,
        areaName: '',
        isTemp: true,
        createTime: this.formatDate(now),
        hasChildren: false // 子项没有子项（最多两层）
      };

      // 添加到列表
      this.detailList.push(newChildItem);

      // 设置父项有子项标记
      this.$set(row, 'hasChildren', true);

      // 确保父项展开
      row.expanded = true;

      // 刷新表格
      this.tableKey = new Date().getTime();

      // 刷新表头汇总数据
      this.calcHeaderFields();

      this.$message.success("子节点添加成功");
    },
    // 确定采购
    handleConfirmPurchase(row) {
      // 前置校验
      if (!row.vendorName || row.vendorName.trim() === '') {
        this.$message.error("供应商不能为空");
        return;
      }

      if (!row.quantity || row.quantity <= 0) {
        this.$message.error("采购总数必须大于0");
        return;
      }

      if (!row.purchasedQuantity || row.purchasedQuantity <= 0) {
        this.$message.error("已购数量必须大于0");
        return;
      }

      if (!row.unitPrice || row.unitPrice <= 0) {
        this.$message.error("单价金额必须大于0");
        return;
      }
      // 设置采购状态为采购中
      row.purchaseCode = 3;
      console.log('确定采购0000---', row);
      // 更新相关金额
      this.updateTotalWithTax(row);
      console.log('确定采购222---', row);
      // 刷新表头汇总数据
      this.calcHeaderFields();
      console.log('确定采购333---', row);
    },
    // 取消采购
    handleCancelPurchase(row) {
      this.$modal.confirm('确定要取消采购操作吗？').then(() => {
        // 设置采购状态为取消采购
        row.purchaseCode = 1;

        // 重置已购数量
        row.purchasedQuantity = 0;
        row.unpurchasedQuantity = row.quantity;

        // 更新相关金额
        this.updateTotalWithTax(row);

        // 刷新表头汇总数据
        this.calcHeaderFields();

        this.$message.success("采购取消成功");
      }).catch(() => {
        this.$message.info("已取消操作");
      });
    },
    // 批量删除
    handleDeleteBatch() {
      const selectedRows = this.delDetails;

      if (!selectedRows || selectedRows.length === 0) {
        this.$message.warning('请选择要删除的子项。');
        return;
      }

      console.log('批量删除选中的行:', selectedRows);

      // 检查删除权限
      const nodesToDelete = [];
      const nodesWithRestrictions = [];

      selectedRows.forEach(row => {
        if (row.parentId) {
          // 子节点：直接检查当前节点的采购状态
          if (row.purchaseCode >= 3) {
            nodesWithRestrictions.push({
              node: row,
              reason: '子节点采购状态 >= 3'
            });
          } else {
            nodesToDelete.push(row);
          }
        } else {
          // 主节点：检查主节点本身和所有子节点的采购状态
          let canDelete = true;
          const restrictedChildren = [];

          // 检查主节点本身
          if (row.purchaseCode >= 3) {
            canDelete = false;
            nodesWithRestrictions.push({
              node: row,
              reason: '主节点采购状态 >= 3'
            });
          }

          // 检查子节点
          if (row.children && row.children.length > 0) {
            row.children.forEach(child => {
              if (child.purchaseCode >= 3) {
                canDelete = false;
                restrictedChildren.push(child);
              }
            });
          }

          if (canDelete) {
            nodesToDelete.push(row);
          } else if (restrictedChildren.length > 0) {
            nodesWithRestrictions.push({
              node: row,
              reason: `主节点包含采购状态 >= 3 的子节点：${restrictedChildren.map(child =>
                child.itemName || child.itemCode || `子节点${child.id}`
              ).join('、')}`
            });
          }
        }
      });

      // 如果有节点不符合删除条件，阻止删除
      if (nodesWithRestrictions.length > 0) {
        this.$modal.msgError(`删除失败，只能删除草稿状态和取消采购状态子项`);
        return;
      }

      // 1. 收集所有要删除的节点（包括子节点）
      const allIdsToDelete = new Set();
      const realIdsToDelete = new Set();
      const tempIdsToDelete = new Set();

      // 存储受影响的父节点（用于刷新）
      const affectedParents = new Set();

      // 递归收集节点及其后代
      const collectNodeAndDescendants = (node) => {
        if (!node || allIdsToDelete.has(node.id)) return;

        allIdsToDelete.add(node.id);

        // 记录父节点（用于后续刷新）
        if (node.parentId) {
          affectedParents.add(node.parentId);
        }

        if (this.isTemporaryId(node.id)) {
          tempIdsToDelete.add(node.id);
        } else {
          realIdsToDelete.add(node.id);
        }

        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          node.children.forEach(child => collectNodeAndDescendants(child));
        }
      };

      // 处理每个选中的行
      nodesToDelete.forEach(row => {
        collectNodeAndDescendants(row);
      });

      // 2. 从 detailList 中删除所有匹配的节点
      this.detailList = this.detailList.filter(item =>
        !allIdsToDelete.has(item.id)
      );

      // 3. 更新受影响父节点的 children 和 hasChildren 状态
      const updatedParents = new Set();

      // 处理每个受影响的父节点
      affectedParents.forEach(parentId => {
        const parent = this.detailList.find(item => item.id === parentId);
        if (parent) {
          // 过滤掉已删除的子节点
          if (parent.children) {
            parent.children = parent.children.filter(child =>
              !allIdsToDelete.has(child.id)
            );
          }

          // 更新 hasChildren 状态
          const hasChildren = parent.children && parent.children.length > 0;
          this.$set(parent, 'hasChildren', hasChildren);

          // 标记需要刷新
          updatedParents.add(parent);
        }
      });

      // 4. 清空选中状态
      if (this.$refs.treeTable) {
        this.$refs.treeTable.clearSelection();
      }

      // 5. 删除持久化数据
      const realIds = Array.from(realIdsToDelete);
      if (realIds.length > 0) {
        delOrderDetail(realIds)
          .then(() => {
            console.log(`成功删除 ${realIds.length} 个持久化项`);
          })
          .catch(err => {
            console.error('删除接口失败:', err);
          });
      }

      // 6. 重置选择
      this.delDetails = [];

      // 7. 刷新所有受影响的父节点
      this.refreshAffectedParents(Array.from(updatedParents));

      // 8. 重新计算表头汇总数据
      this.calcHeaderFields();

      console.log(`已删除 ${allIdsToDelete.size} 个节点`);
    },
    // 刷新受影响的父节点
    refreshAffectedParents(parents) {
      this.$nextTick(() => {
        if (this.$refs.treeTable && parents.length > 0) {
          // 创建新的 tableKey 强制刷新表格
          this.tableKey = `table_${Date.now()}`;

          // 展开并刷新每个受影响的父节点
          parents.forEach(parent => {
            // 确保父节点保持展开状态
            this.$refs.treeTable.toggleRowExpansion(parent, true);

            // 刷新父节点行
            this.$refs.treeTable.store.updateChildren(parent);
          });
        }
      });
    },
    isTemporaryId(id) {
      console.log('isTemporaryId--number');
      // null, undefined
      if (id == null) return true;

      // 字符串类型
      if (typeof id === 'string') {
        console.log('isTemporaryId--字符串');
        const trimmed = id.trim();
        // 以 'temp_' 开头 或 不是纯数字
        return trimmed.startsWith('temp_') || !/^\d+$/.test(trimmed);
      }

      // 数字类型
      if (typeof id === 'number') {
        console.log('isTemporaryId--number');
        // 非整数 或 小于 0
        return !Number.isInteger(id) || id < 0;
      }

      // 其他类型（如 boolean, array, object）都认为是临时的
      return true;
    },
    // 点击搜索或聚焦输入框时，打开供应商选择
    // 来自表格行点击
    handleSelectVendorFromTable(row, index) {
      console.log('handleSelectVendorFromTable - row:', row, 'index:', index);
      console.log('当前行是否为父项:', !row.parentId);
      console.log('当前行的parentId:', row.parentId);

      if (this.isDetailActionDisabled(row)) return;

      this.currentEditSource = 'table';
      this.currentTableRow = row;
      this.currentTableIndex = index;

      console.log('设置当前编辑源为表格，当前行:', this.currentTableRow);

      // 打开供应商选择器
      this.$refs.vendorSelect.itemId = row.itemId; // 可选：传参过滤
      this.$refs.vendorSelect.showFlag = true;
    },
    // 来自编辑弹窗点击
    handleSelectVendorFromDialog() {
      if (this.isDetailActionDisabled(this.editDetailForm)) return;

      this.currentEditSource = 'dialog';

      // 打开供应商选择器
      this.$refs.vendorSelect.itemId = this.editDetailForm.itemId;
      this.$refs.vendorSelect.showFlag = true;
    },
    // 供应商选择回调
    onVendorSelected(vendor) {
      console.log('供应商选择回调 - vendor:', vendor);
      console.log('当前编辑源:', this.currentEditSource);
      console.log('当前表格行:', this.currentTableRow);

      if (this.currentEditSource === 'table' && this.currentTableRow) {
        // 回填到表格行
        console.log('回填到表格行 - 之前:', {
          vendorId: this.currentTableRow.vendorId,
          vendorName: this.currentTableRow.vendorName,
          vendorCode: this.currentTableRow.vendorCode
        });

        // 更新当前表格行
        this.$set(this.currentTableRow, 'vendorId', vendor.vendorId);
        this.$set(this.currentTableRow, 'vendorName', vendor.vendorName);
        this.$set(this.currentTableRow, 'vendorCode', vendor.vendorCode);

        console.log('回填到表格行 - 之后:', {
          vendorId: this.currentTableRow.vendorId,
          vendorName: this.currentTableRow.vendorName,
          vendorCode: this.currentTableRow.vendorCode
        });

        // 同时更新detailList中的对应项
        const detailItem = this.detailList.find(item => item.id === this.currentTableRow.id);
        if (detailItem) {
          this.$set(detailItem, 'vendorId', vendor.vendorId);
          this.$set(detailItem, 'vendorName', vendor.vendorName);
          this.$set(detailItem, 'vendorCode', vendor.vendorCode);
          console.log('同时更新detailList中的项:', detailItem);
        }

        // 强制更新视图
        this.$forceUpdate();

        // 更新表格key以强制重新渲染
        this.tableKey = new Date().getTime();

        // 等待DOM更新后验证数据
        this.$nextTick(() => {
          // 验证数据是否正确保存到detailList
          const updatedItem = this.detailList.find(item => item.id === this.currentTableRow.id);
          console.log('验证detailList中的数据:', updatedItem);

          // 验证表格中显示的数据
          console.log('表格中当前行的数据:', this.currentTableRow);
        });

      } else if (this.currentEditSource === 'dialog') {
        // 回填到编辑弹窗
        console.log('回填到编辑弹窗 - 之前:', {
          vendorId: this.editDetailForm.vendorId,
          vendorName: this.editDetailForm.vendorName,
          vendorCode: this.editDetailForm.vendorCode
        });

        this.editDetailForm.vendorId = vendor.vendorId;
        this.editDetailForm.vendorName = vendor.vendorName;
        this.editDetailForm.vendorCode = vendor.vendorCode;

        console.log('回填到编辑弹窗 - 之后:', {
          vendorId: this.editDetailForm.vendorId,
          vendorName: this.editDetailForm.vendorName,
          vendorCode: this.editDetailForm.vendorCode
        });
      }

      // 清空状态
      this.currentEditSource = null;
      this.currentTableRow = null;
      this.currentTableIndex = null;
    },
    // 编辑弹窗中已购数量变化处理
    handleEditPurchasedQuantityChange() {
      // 计算未购数量
      this.calcUnpurchasedQuantity(this.editDetailForm);
      // 刷新表头汇总数据
      this.calcHeaderFields();
    },
    // 编辑采购单子项弹窗：保存
    saveEditDetail() {
      // 校验表单
      this.$refs.editDetailFormRef.validate((valid) => {
        if (!valid) {
          this.$message.error('请完善表单，供应商为必填项');
          return;
        }
        // 最后检查并自动更新状态
        this.checkAndUpdatePurchaseStatus(this.editDetailForm);
        // 更新 detailList 中对应项
        if (this.editDetailIndex !== null && this.editDetailIndex >= 0) {
          this.$set(this.detailList, this.editDetailIndex, { ...this.editDetailForm });
        }
        this.editDetailDialogVisible = false;
        this.editDetailForm = {};
        this.editDetailIndex = null;
        this.calcHeaderFields();
      });
    },
    // 编辑采购单子项弹窗：取消
    cancelEditDetail() {
      this.editDetailDialogVisible = false;
      this.editDetailForm = {};
      this.editDetailIndex = null;
    },
    // 提交或保存时调用
    validateDetailList() {
      for (let i = 0; i < this.detailList.length; i++) {
        const row = this.detailList[i];
        if (!row.vendorName || !row.vendorId) {
          this.$message.error(`第 ${i + 1} 行：请选择供应商`);
          return false;
        }
      }
      return true;
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          //采购状态为采购中保存的时候则 需要 供应商状态填写
          if (this.form.purchaseCode >= 3) {
            // ✅ 校验明细列表
            if (!this.validateDetailList()) {
              return; // 校验失败，中断提交
            }
          }

          // ✅ 所有校验通过
          const purchase = this.clearIdIfTemporary(this.form);

          // 构建树状结构 details
          const details = this.buildTreeStructure();
          const delDetailIds = this.delDetailIds;
          const addType = 1;//保存
          purchase.purchaseCode = 2;
          const submitData = {
            purchase,
            details,  // 使用树状结构
            delDetailIds,
            addType//保存
          };

          console.log('------submitForm -----submitData,', submitData);
          addAllPurchase(submitData)
            .then(() => {
              this.$modal.msgSuccess("保存成功");
              this.showEditArea = false;
              this.getList();
            })
            .catch(error => {
              this.$modal.msgError("保存失败：" + (error.message || "请求异常"));
              console.error("提交采购单失败", error);
            });
        }
      });
    },
    submitFormRequest() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // ✅ 所有校验通过
          const purchase = this.clearIdIfTemporary(this.form);
          purchase.purchaseCode = 3;
          // 构建树状结构 details
          const details = this.buildTreeStructure();
          const delDetailIds = this.delDetailIds;
          const addType = 2;//提交采购
          const submitData = {
            purchase,
            details,  // 使用树状结构
            delDetailIds,
            addType//提交采购
          };

          console.log('------submitForm -----submitData,', submitData);
          addAllPurchase(submitData)
            .then(() => {
              this.$modal.msgSuccess("保存成功");
              this.showEditArea = false;
              this.getList();
            })
            .catch(error => {
              this.$modal.msgError("保存失败：" + (error.message || "请求异常"));
              console.error("提交采购单失败", error);
            });
        }
      });
    },
    // 构建树状结构
    buildTreeStructure() {
      // 1. 创建节点映射
      const nodeMap = {};
      this.detailList.forEach(item => {
        const cleaned = this.clearIdIfTemporary(item);
        nodeMap[item.id] = cleaned;
        cleaned.children = []; // 初始化子节点数组
      });

      // 2. 构建树
      const tree = [];
      this.detailList.forEach(item => {
        const cleaned = nodeMap[item.id];

        if (item.parentId) {
          // 添加到父节点
          const parent = nodeMap[item.parentId];
          if (parent) {
            parent.children.push(cleaned);
          } else {
            // 父节点不存在，作为根节点处理
            tree.push(cleaned);
          }
        } else {
          // 根节点
          tree.push(cleaned);
        }
      });

      return tree;
    },
    /**
     * 如果 item.id 是临时的，则清空 id，并删除临时标记字段
     */
    clearIdIfTemporary(item) {
      const { id, _isTemp, isTemp, parentId, ...rest } = item;

      // 如果是临时 ID，则不包含 id 字段（或设为 null）
      if (this.isTemporaryId(id)) {
        return rest; // 不返回 id 字段（推荐），或返回 { ...rest, id: null }
      }

      // 否则保留原始 id
      return { ...rest, id };
    },

    // 获取仓库列表
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);
        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },

    // 生成入库批次号（当前年月日）
    generateInboundBatchCode() {
      const now = new Date();
      const y = now.getFullYear();
      const m = String(now.getMonth() + 1).padStart(2, '0');
      const d = String(now.getDate()).padStart(2, '0');
      return `${y}${m}${d}`;
    },

    // 处理入库批次号变化
    handleInboundBatchCodeChange(value, row) {
      row.inboundBatchCode = value;
    },

    // 处理仓库选择变化
    handleWarehouseChanged(value, row) {
      console.log('仓库选择变化value:', value);
      console.log('仓库选择变化row:',  row);
      if (value && value.length >= 3) {
        row.warehouseId = value[0];
        row.locationId = value[1];
        row.areaId = value[2];
        
        // 根据选择的仓库信息更新显示名称和编码
        const warehouse = this.findWarehouseById(value[0]);
        const location = this.findLocationById(value[1]);
        const area = this.findAreaById(value[2]);
        
        if (warehouse) {
          row.warehouseName = warehouse.pName;
          row.warehouseCode = warehouse.pCode || warehouse.code;
        }
        if (location) {
          row.locationName = location.pName;
          row.locationCode = location.pCode || location.code;
        }
        if (area) {
          row.areaName = area.pName;
          row.areaCode = area.pCode || area.code;
        }
        
        console.log('更新后的仓库信息:', {
          warehouseId: row.warehouseId,
          locationId: row.locationId,
          areaId: row.areaId,
          warehouseName: row.warehouseName,
          locationName: row.locationName,
          areaName: row.areaName,
          warehouseCode: row.warehouseCode,
          locationCode: row.locationCode,
          areaCode: row.areaCode
        });
      } else {
        row.warehouseId = null;
        row.locationId = null;
        row.areaId = null;
        row.warehouseName = '';
        row.locationName = '';
        row.areaName = '';
        row.warehouseCode = '';
        row.locationCode = '';
        row.areaCode = '';
      }
    },

    // 根据ID查找仓库
    findWarehouseById(id) {
      return this.warehouseOptions.find(w => w.pId === id);
    },

    // 根据ID查找库区
    findLocationById(id) {
      for (const warehouse of this.warehouseOptions) {
        if (warehouse.children) {
          const location = warehouse.children.find(l => l.pId === id);
          if (location) return location;
        }
      }
      return null;
    },

    // 根据ID查找库位
    findAreaById(id) {
      for (const warehouse of this.warehouseOptions) {
        if (warehouse.children) {
          for (const location of warehouse.children) {
            if (location.children) {
              const area = location.children.find(a => a.pId === id);
              if (area) return area;
            }
          }
        }
      }
      return null;
    },

    // 判断入库按钮是否禁用
    isInboundButtonDisabled(row) {
      // 条件1: purchaseCode=7 或 purchaseCode=8
      if (row.purchaseCode === 7 || row.purchaseCode === 8) {
        return true;
      }
      
      // 条件2: purchasedQuantity-receivedQuantity<=0 (待收数量<=0)
      const purchasedQuantity = parseFloat(row.purchasedQuantity) || 0;
      const receivedQuantity = parseFloat(row.receivedQuantity) || 0;
      const waitedQuantity = purchasedQuantity - receivedQuantity;
      
      if (waitedQuantity <= 0) {
        return true;
      }
      
      return false;
    },
    // 判断入库按钮是否禁用
    isInboundButtonDisabledForCode(row) {
      // 条件1: purchaseCode=7 或 purchaseCode=8
      if (row.purchaseCode === 7 || row.purchaseCode === 8) {
        return true;
      }
      
      // 条件2: purchasedQuantity-receivedQuantity<=0 (待收数量<=0)
      const purchasedQuantity = parseFloat(row.purchasedQuantity) || 0;
      const receivedQuantity = parseFloat(row.receivedQuantity) || 0;
      const waitedQuantity = purchasedQuantity - receivedQuantity;
      
      if (waitedQuantity <= 0) {
        return true;
      }
      
      return false;
    },
    // 处理入库操作
    handleInbound(row) {

      console.log('---handleInbound---入库操作',row);
      // 验证主表单的采购状态 (>=3 且 <=6)
      if (this.form.purchaseCode < 3 || this.form.purchaseCode > 6) {
        this.$message.warning('此采购状态不能进行入库操作');
        return;
      }
      if (row.purchaseCode < 3 || row.purchaseCode > 6) {
        this.$message.warning('此采购状态不能进行入库操作');
        return;
      }
      // 验证入库批次号
      if (!row.inboundBatchCode || row.inboundBatchCode.trim() === '') {
        this.$message.warning('请先填写入库批次号');
        return;
      }
      
      // 验证仓库信息
      if (!row.warehouseId) {
        this.$message.warning('请先选择仓库');
        return;
      }
      if (!row.locationId) {
        this.$message.warning('请先选择库区');
        return;
      }
      if (!row.areaId) {
        this.$message.warning('请先选择库位');
        return;
      }
      
      // 验证已收数量
      if (!row.receivedQuantity || parseFloat(row.receivedQuantity) <= 0) {
        this.$message.warning('已收数量必须大于0才能入库');
        return;
      }
      
      this.$modal.confirm(`确认要执行入库操作吗？\n物料：${row.itemName}\n数量：${row.receivedQuantity}\n批次号：${row.inboundBatchCode}\n仓库：${row.warehouseName}\n库区：${row.locationName}\n库位：${row.areaName}`).then(() => {
        // 执行计算和状态更新
        const purchasedQuantity = parseFloat(row.purchasedQuantity) || 0;
        const receivedQuantity = parseFloat(row.receivedQuantity) || 0;
        const unitPrice = parseFloat(row.unitPrice) || 0;
        const paidAmount = parseFloat(row.paidAmount) || 0;
        const billCode = parseInt(row.billCode) || 0;
        
        // 计算待收数量
        const waitedQuantity = purchasedQuantity - receivedQuantity;
        row.waitedQuantity = parseFloat(waitedQuantity.toFixed(2));
        
        // 计算总金额（不含税）
        const totalWithoutTax = unitPrice * purchasedQuantity;
        row.totalWithoutTax = parseFloat(totalWithoutTax.toFixed(2));
        
        // 计算应付金额
        const payableAmount = totalWithoutTax - paidAmount;
        row.payableAmount = parseFloat(payableAmount.toFixed(2));
        
        // 根据条件更新采购状态
        if (purchasedQuantity > 0 && waitedQuantity > 0) {
          row.purchaseCode = 5; // 收货中
          console.log(`采购子项 ${row.itemName || row.id} 状态更新为: 收货中 (5)`);
        } else if (purchasedQuantity > 0 && waitedQuantity <= 0 && billCode === 2) {
          row.purchaseCode = 8; // 处理完成
          console.log(`采购子项 ${row.itemName || row.id} 状态更新为: 处理完成 (8)`);
        } else if (purchasedQuantity > 0 && waitedQuantity <= 0 && billCode === 1) {
          row.purchaseCode = 7; // 带补票据
          console.log(`采购子项 ${row.itemName || row.id} 状态更新为: 带补票据 (7)`);
        }
        
        // 调用入库API
        const storeData = {
          itemId: row.itemId,
          itemCode: row.itemCode,
          itemName: row.itemName,
          itemImgUrl:row.itemImgUrl,
          unitOfMeasure:row.unitOfMeasure,
          itemOrProduct:row.itemOrProduct,
          specification:row.specification,
          quantity:parseFloat(row.quantity),//采购数量
          purchasedQuantity:parseFloat(row.purchasedQuantity),//已购数量
          waitedQuantity:parseFloat(row.waitedQuantity),//待收数量
          receivedQuantity: parseFloat(row.receivedQuantity),//已收
          totalWithoutTax: parseFloat(row.totalWithoutTax),//总金额（不含税）
          payableAmount: parseFloat(row.payableAmount),//应付金额
          inboundBatchCode: row.inboundBatchCode,
          warehouseId: row.warehouseId,
          warehouseName: row.warehouseName,
          locationId: row.locationId,
          locationName: row.locationName,
          areaId: row.areaId,
          areaName: row.areaName,
          purchaseId: this.form.id,
          id:row.id,
          vendorId:row.vendorId,//供应商
          vendorCode:row.vendorCode,
          vendorName:row.vendorName,
          purchaseCode:row.purchaseCode,
          billCode:row.billCode
        };
        
        console.log('执行入库操作:', storeData);
        
        // 调用 toSaveStore 方法
        toSaveStore(storeData).then(response => {
          this.$message.success('入库操作成功');
          // 刷新数据
          this.getDetailListPage(this.form.id);
        }).catch(error => {
          this.$message.error('入库操作失败：' + (error.message || '请求异常'));
          console.error('入库操作失败', error);
        });
      }).catch(() => {
        this.$message.info('已取消入库操作');
      });
    }
  }
};
</script>

<style scoped>
/* 弹窗内容可滚动 */
.dialog-content-wrapper {
  max-height: calc(100vh - 80px);
  min-height: 600px;
  overflow: auto;
  padding: 0 10px 10px;
  box-sizing: border-box;
}

/* 响应式 dialog 样式 */
::v-deep .responsive-dialog {
  min-width: 600px;
}

/* 小屏幕适配 */
@media (max-width: 768px) {
  ::v-deep .responsive-dialog {
    width: 95% !important;
    margin: 10px auto !important;
  }

  ::v-deep .el-col-12 {
    width: 100%;
    margin-bottom: 10px;
  }

  ::v-deep .el-form-item__label {
    padding-bottom: 0;
    line-height: 32px;
  }

  ::v-deep .el-button + .el-button {
    margin-left: 5px;
  }
}

/* 中等屏幕 */
@media (min-width: 769px) and (max-width: 1024px) {
  ::v-deep .responsive-dialog {
    width: 85% !important;
  }
  .dialog-content-wrapper {
    max-height: calc(100vh - 180px);
  }
}

/* 大屏 */
@media (min-width: 1025px) {
  ::v-deep .responsive-dialog {
    width: 70% !important;
  }
  .dialog-content-wrapper {
    max-height: calc(100vh - 200px);
  }
}

/* 垂直滚动条整体样式 */
.dialog-content-wrapper::-webkit-scrollbar {
  width: 15px; /* 控制垂直滚动条的宽度 */
  height: 6px; /* 控制水平滚动条的高度（如果有） */
}
/* 滚动条滑块（可拖动部分） */
.dialog-content-wrapper::-webkit-scrollbar-thumb {
  background-color: #c0c0c0;
  border-radius: 4px;
}
/* 滚动条轨道 */
.dialog-content-wrapper::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}
.dialog-content-wrapper .form-row {
  margin-bottom: 8px;
}
.dialog-content-wrapper .form-row:last-child {
  margin-bottom: 12px;
}

/* 树形表格层级样式 */
::v-deep .el-table__expand-icon {
  margin-right: 8px;
}

::v-deep .el-table__expand-icon .el-table__expand-icon-inner {
  font-size: 12px;
  color: #409eff;
}

/* 父项行样式 */
::v-deep .el-table__row--level-0 {
  background-color: #fafafa;
  font-weight: 500;
}

/* 子项行样式 */
::v-deep .el-table__row--level-1 {
  background-color: #ffffff;
  padding-left: 20px;
}

/* 状态标签样式 */
::v-deep .el-tag {
  font-weight: 500;
}

/* 未购数量样式 */
.unpurchased-quantity {
  font-weight: bold;
}

.unpurchased-quantity.warning {
  color: #e6a23c;
}

.unpurchased-quantity.success {
  color: #67c23a;
}

/* 采购状态标签样式 */
::v-deep .purchase-status-cancelled {
  background-color: #fff2f0 !important;
  border-color: #ffccc7 !important;
  color: #cf1322 !important;
  font-weight: 600;
}

::v-deep .purchase-status-draft {
  background-color: #f5f5f5 !important;
  border-color: #d9d9d9 !important;
  color: #8c8c8c !important;
  font-weight: 600;
}

::v-deep .purchase-status-purchasing {
  background-color: #fff7e6 !important;
  border-color: #ffd591 !important;
  color: #d46b08 !important;
  font-weight: 600;
}

::v-deep .purchase-status-ordered {
  background-color: #f0f9ff !important;
  border-color: #91d5ff !important;
  color: #1890ff !important;
  font-weight: 600;
}

::v-deep .purchase-status-receiving {
  background-color: #fff7e6 !important;
  border-color: #ffd591 !important;
  color: #d46b08 !important;
  font-weight: 600;
}

::v-deep .purchase-status-shipped {
  background-color: #e6f7ff !important;
  border-color: #91d5ff !important;
  color: #1890ff !important;
  font-weight: 600;
}

::v-deep .purchase-status-pending-bill {
  background-color: #fff2f0 !important;
  border-color: #ffccc7 !important;
  color: #cf1322 !important;
  font-weight: 600;
}

::v-deep .purchase-status-completed {
  background-color: #f6ffed !important;
  border-color: #b7eb8f !important;
  color: #389e0d !important;
  font-weight: 600;
}

::v-deep .purchase-status-unknown {
  background-color: #f5f5f5 !important;
  border-color: #d9d9d9 !important;
  color: #8c8c8c !important;
  font-weight: 500;
}

/* 行状态样式 */
::v-deep .row-cancelled {
  background-color: #fafafa !important;
}

::v-deep .row-draft {
  background-color: #f5f5f5 !important;
}

/* 草稿状态禁用样式 */
::v-deep .disabled-row {
  opacity: 0.6 !important;
  pointer-events: none !important;
}

::v-deep .disabled-row .el-input__inner,
::v-deep .disabled-row .el-input-number__decrease,
::v-deep .disabled-row .el-input-number__increase,
::v-deep .disabled-row .el-select .el-input__inner {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #c0c4cc !important;
  cursor: not-allowed !important;
}

::v-deep .disabled-row .el-button {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #c0c4cc !important;
  cursor: not-allowed !important;
}

::v-deep .disabled-row .el-button:hover {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #c0c4cc !important;
}

::v-deep .row-purchasing {
  background-color: #fff7e6 !important;
}

::v-deep .row-ordered {
  background-color: #f0f9ff !important;
}

::v-deep .row-receiving {
  background-color: #fff7e6 !important;
}

::v-deep .row-shipped {
  background-color: #e6f7ff !important;
}

::v-deep .row-pending-bill {
  background-color: #fff2f0 !important;
}

::v-deep .row-completed {
  background-color: #f6ffed !important;
}

/* 查看弹窗样式 */
::v-deep .el-dialog__body {
  padding: 10px 20px;
}

/* 查看模式下的表单样式 */
::v-deep .el-form.is-disabled .el-form-item__label {
  color: #606266;
  font-weight: 500;
}

::v-deep .el-form.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

/* 附件链接样式 */
.attachment-link {
  color: #409eff;
  text-decoration: none;
}

.attachment-link:hover {
  color: #66b1ff;
  text-decoration: underline;
}

/* 查看弹窗中的表格样式 */
::v-deep .el-table--border th {
  background-color: #fafafa;
}

/* 查看模式下的按钮样式 */
::v-deep .el-button.is-disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
}

/* 仓库选择器样式 */
::v-deep .el-cascader {
  width: 100%;
}

::v-deep .el-cascader .el-input__inner {
  font-size: 12px;
  padding: 0 8px;
  height: 28px;
  line-height: 28px;
}

/* 入库相关字段样式 */
.inbound-fields {
  .el-input,
  .el-cascader {
    width: 100%;
  }
}

/* 表格中所有输入框的统一样式 */
::v-deep .el-table .el-input__inner {
  font-size: 12px;
  padding: 0 8px;
  height: 28px;
  line-height: 28px;
}

/* 表格中数字输入框的统一样式 */
::v-deep .el-table .el-input-number {
  width: 100%;
}

::v-deep .el-table .el-input-number .el-input__inner {
  font-size: 12px;
  padding: 0 8px;
  height: 28px;
  line-height: 28px;
}

/* 确保仓库、库区、库位字段显示完整 */
::v-deep .el-table .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}

/* 仓库选择器下拉框样式 */
::v-deep .el-cascader__dropdown {
  max-height: 300px;
}

::v-deep .el-cascader__dropdown .el-cascader-node {
  height: 32px;
  line-height: 32px;
  padding: 0 12px;
}

/* 表格单元格内容垂直居中 */
::v-deep .el-table .cell {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 32px;
}

/* 确保表格可以水平滚动 */
::v-deep .el-table {
  overflow-x: auto;
}

/* 入库相关列的样式优化 */
::v-deep .el-table .el-table__body-wrapper {
  overflow-x: auto;
}

/* 仓库选择器在表格中的样式 */
::v-deep .el-table .el-cascader {
  width: 100%;
  min-width: 200px;
}

/* 入库批次号输入框样式 */
::v-deep .el-table .el-input {
  width: 100%;
}

/* 确保文本在输入框中完整显示 */
::v-deep .el-table .el-input__inner {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

/* 表格行高度调整 */
::v-deep .el-table .el-table__row {
  height: 40px;
}

/* 入库字段的容器样式 */
.inbound-column {
  min-width: 150px;
  max-width: 300px;
}

/* 确保入库按钮显示为绿色 */
::v-deep .el-button--success {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
  color: #ffffff !important;
}

::v-deep .el-button--success:hover,
::v-deep .el-button--success:focus {
  background-color: #85ce61 !important;
  border-color: #85ce61 !important;
  color: #ffffff !important;
}

::v-deep .el-button--success:active {
  background-color: #5daf34 !important;
  border-color: #5daf34 !important;
  color: #ffffff !important;
}
</style>
